<?php

class GalleryController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','publish'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel()->delete();
                        $name = Yii::app()->params['imageHomeAbs'].$_GET['filename'];
                        unlink($name);

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

        public function actionPublish()
	{
			// we only allow deletion via POST request
                        $model=$this->loadModel();
                        if ($model->status=='Publish'){
                            Gallery::model()->updateByPk($_GET['id'],array('status'=>'Unpublish'));
                            //$this->refresh();
                        } else {
                            Gallery::model()->updateByPk($_GET['id'],array('status'=>'Publish'));
                            //$this->refresh();
                        }
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}


	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Gallery;
		//$model->unsetAttributes();  // clear any default values
		//if(isset($_GET['Gallery']))
		//	$model->attributes=$_GET['Gallery'];
                if(isset($_POST['Gallery'])) {
                  $model->attributes=$_POST['Gallery'];
                  $model->image=CUploadedFile::getInstance($model,'image');
                  if ($model->validate()) {
                    $name = $model->image->name;
                    if (file_exists(Yii::app()->params['imageHomeAbs'].$name)) {
                      // already there
                      $v = 2;
                      preg_match('/(\w+)\.(\w+)/', $name, $match);
                      do {
                        $name = $match[1].'('.$v++.').'.$match[2];
                      } while (file_exists(Yii::app()->params['imageHomeAbs'].$name));
                    }
                    if ($model->validate()) {
                      $model->image->saveAs(Yii::app()->params['imageHomeAbs'].$name);
                      $model->image=$name;
                      $model->status='Publish';
                      $model->save();
                      $this->refresh();
                    }
                  }
                }
                 
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=Gallery::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='gallery-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
